import { defineStore } from "pinia";
import { ref } from "vue";
import { fetchDictByType } from "@/api";

export const useDictStore = defineStore("dict", () => {
  const dictMap = ref({}); // 缓存字典数据：{ product: [...], channel: [...] }
  const lastLoadedAt = ref({}); // 每种类型的加载时间
  const loadingPromises = {}; // 正在加载中的字典请求（防止并发）
  let autoRefreshTimer = null; // 自动刷新定时器

  const CACHE_DURATION = 30 * 60 * 1000; // 缓存有效期：30分钟

  // 加载字典（带缓存、去重、过期判断）
  const loadDict = async (type) => {
    const lastTime = lastLoadedAt.value[type];

    // 缓存有效，直接返回
    if (
      dictMap.value[type] &&
      lastTime &&
      Date.now() - lastTime.getTime() < CACHE_DURATION
    ) {
      return dictMap.value[type];
    }

    // 防止重复请求
    if (loadingPromises[type]) {
      return loadingPromises[type];
    }

    loadingPromises[type] = fetchDictByType(type)
      .then((data) => {
        dictMap.value[type] = data;
        lastLoadedAt.value[type] = new Date();
        delete loadingPromises[type];

        // 成功加载后，自动启动刷新
        if (!autoRefreshTimer) startAutoRefresh();

        return data;
      })
      .catch((err) => {
        delete loadingPromises[type];
      });

    return loadingPromises[type];
  };

  // 主动刷新某个字典（不看缓存）
  const reloadDict = async (type) => {
    if (loadingPromises[type]) {
      return loadingPromises[type];
    }

    loadingPromises[type] = fetchDictByType(type)
      .then((data) => {
        dictMap.value[type] = data;
        lastLoadedAt.value[type] = new Date();
        delete loadingPromises[type];

        // 也触发刷新
        if (!autoRefreshTimer) startAutoRefresh();

        return data;
      })
      .catch((err) => {
        delete loadingPromises[type];
        throw err;
      });

    return loadingPromises[type];
  };

  // 启动自动刷新（每30分钟刷新一次所有已加载类型）
  const startAutoRefresh = () => {
    stopAutoRefresh();
    autoRefreshTimer = setInterval(() => {
      const types = Object.keys(dictMap.value);
      types.forEach((type) => reloadDict(type));
    }, CACHE_DURATION);
  };

  // 停止自动刷新
  const stopAutoRefresh = () => {
    if (autoRefreshTimer) {
      clearInterval(autoRefreshTimer);
      autoRefreshTimer = null;
    }
  };

  return {
    dictMap,
    lastLoadedAt,
    loadDict,
    reloadDict,
    startAutoRefresh,
    stopAutoRefresh,
  };
});
